<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
                <!-- 卡片区域-- -->
    <el-card>
    <el-button type="success" @click='addCategory'>添加分类</el-button>
    <!-- 商品分类表格 -->
    <table-tree :data='categoryList' :columns="columns"
    show-index index-text='序号' border :selection-type='false'
    :expand-type='false'
    >
    <!-- 有效判断 -->
    <template slot='isSure' slot-scope="scope">
        <i class="el-icon-success" v-if='scope.row.cat_deleted ===false' style='color:green'></i>
        <i class="el-icon-error" v-else style='color:red'></i>
    </template>
    <!-- 等级 -->
    <template slot='isLevel' slot-scope='scope'>
        <el-tag v-if='scope.row.cat_level===0'>一级</el-tag>
        <el-tag type='success' v-else-if='scope.row.cat_level===1'>二级</el-tag>
        <el-tag type='warning' v-else>三级</el-tag>
    </template>
    <!-- 操作 -->
    <template slot='isDone' slot-scope="scope">
        <el-button type="primary"  size='small' icon="el-icon-edit" @click='toSearchCategory(scope.row)'>编辑</el-button>
        <el-button type="danger" size='small' icon="el-icon-delete" @click='toDeleteCate(scope.row.cat_id)'>删除</el-button>
    </template>
    </table-tree>
    <!-- 分页 -->
      <div class="block">
      <el-pagination
      @current-change="handleCurrentChange"
      :page-size="categoryInfo.pagesize"
      layout="total, prev, pager, next, jumper"
      :current-page="categoryInfo.pegenum"
      :total="total">
    </el-pagination>
      </div>
    </el-card>
    <!-- 添加商品分类模态框 -->
    <el-dialog
  title="添加商品分类"
  :visible.sync="addCategoryVisible" @close='resetForm("addCateRef")'>
  <el-form :model="addCateForm" :rules="addCateRules" ref='addCateRef' label-width="100px" class="demo-ruleForm">
  <el-form-item label="分类名称" prop="cat_name" >
    <el-input v-model="addCateForm.cat_name"></el-input>
  </el-form-item>
  <el-form-item label="父级分类" prop="cat_pid" size='medium' ref='addCateRef'>
    <el-cascader
    :options="categoryList"
    :props="addCateObj"
    clearable
    props.expandTrigger='hover'
    v-model="categoryKey"
    @change='handleChange'
    change-on-select
    ></el-cascader>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addCategoryVisible = false">取 消</el-button>
    <el-button type="primary" @click='toAddCategory'>确 定</el-button>
  </span>
    </el-dialog>
    <!-- 编辑商品分类模态框 -->
    <el-dialog
  title="修改商品分类"
  :visible.sync="editCategoryVisible" @close='resetForm("editCateRef")'>
   <el-form :model="addCateForm" :rules="addCateRules" ref='editCateRef' label-width="100px" class="demo-ruleForm">
  <el-form-item label="分类名称" prop="cat_name" >
    <el-input v-model="addCateForm.cat_name"></el-input>
  </el-form-item>
  <el-form-item label="父级分类"  size='medium' >
    <el-cascader
    :options="categoryList"
    :props="addCateObj"
    clearable
    props.expandTrigger='hover'
    v-model="categoryKey"
    @change='handleChange'
    change-on-select
    ></el-cascader>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editCategoryVisible = false">取 消</el-button>
    <el-button type="primary" @click='toEditCate'>确 定</el-button>
  </span>
    </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      categoryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      //   分类数据id
      categoryKey: [],
      editCategoryKey: [],
      //   添加表单
      addCateForm: {
        // 分类名称
        cat_name: '',
        // 分类等级
        cat_level: 0,
        // 分类id
        cat_pid: 0
      },
      //   根据id获取的数据对象
      editCateForm: {},
      addCateRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 8, message: '长度在 1 到 8 个字符', trigger: 'blur' }
        ]
      },
      //   商品分类列表
      categoryList: [],
      //   总计
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
        // 以template为模板的列
          label: '是否有效',
          prop: 'cat_deleted',
          type: 'template',
          template: 'isSure'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'isLevel'
        },
        {
          label: '操作',
          type: 'template',
          template: 'isDone'
        }
      ],
      //   分类id
      categoryId: 0,
      //   修改模态框显示
      editCategoryVisible: false,
      //   添加模态框显示
      addCategoryVisible: false,
      //   分类名称数组
      cateNameList: [],
      //   分类选项的相关配置对象
      addCateObj: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      }
    }
  },
  created () {
    //   获取商品分类数据
    this.getCategories()
  },
  methods: {
    //   获取商品分类函数
    async getCategories () {
      const data = await this.$http.get('categories', {
        params: this.categoryInfo
      })
      if (data.meta.status !== 200) return this.$message.error('获取商品分类失败')
      this.categoryList = data.data.result
      this.total = data.data.total
    },
    async toSearchCategory (val) {
    //   分类id
      this.categoryId = val.cat_id
      //   模态框显示
      this.editCategoryVisible = true
      //   根据id获取分类数据
      const data = await this.$http.get('categories/' + val.cat_id)
      this.editCateForm = data.data
      const cateKey = [data.data.cat_pid]
      console.log(cateKey)
      this.categoryKey = cateKey
      if (data.meta.status !== 200) return this.$message.error('获取分类数据失败')
    },
    // 修改商品分类
    toEditCate () {
      this.$refs.editCateRef.validate(async (valid) => {
        if (!valid) {
          return this.$Message.error('信息输入错误，请重新输入正确格式')
        } else {
        // 发送添加用户信息请求
          const data = await this.$http.put('categories/' + this.categoryId, this.addCateForm)
          if (data.meta.status === 200) {
            this.$message.success('修改用户成功')
            this.editCategoryVisible = false
            this.getCategories()
          } else {
            this.$Message.error('修改用户失败')
          }
        }
      })
    },
    // 改变页码重新获取数据
    handleCurrentChange (val) {
      this.categoryInfo.pagenum = val
      this.getCategories()
    },
    // 点击添加商品分类
    addCategory () {
      this.getCategories_add()
      this.addCategoryVisible = true
    },
    // 添加商品分类之前获取商品分类---只需前两级分类
    async getCategories_add () {
      const data = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (data.meta.status !== 200) return this.$message.error('获取商品分类失败')
      this.categoryList = data.data
    },
    // 当选中分类改变时通过change方法去查询选中的分类
    handleChange () {
      console.log(this.categoryKey)
      if (this.categoryKey.length > 0) {
        this.addCateForm.cat_pid = this.categoryKey[this.categoryKey.length - 1]
        this.addCateForm.cat_level = this.categoryKey.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 校验表单并添加商品分类
    toAddCategory () {
      this.$refs.addCateRef.validate(async (valid) => {
        if (!valid) {
          return this.$Message.error('信息输入错误，请重新输入正确格式')
        } else {
        // 发送添加用户信息请求
          const data = await this.$http.post('categories', this.addCateForm)
          if (data.meta.status === 201) {
            this.$message.success('创建用户成功')
            this.addCategoryVisible = false
            this.getCategories()
          } else {
            this.$Message.error('创建用户失败')
          }
        }
      })
    },
    // 删除商品分类
    toDeleteCate (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.$http.delete('categories/' + id)
        this.getCategories()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 重置表单分类
    resetForm (val) {
      this.$refs[val].resetFields()
      this.categoryKey = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    }
  }
}
</script>

<style lang="less" scoped>
.zk-table {
    margin-top: 10px!important;
}
.el-pagination {
    width:100%;
}
</style>
